package cn.edu.xmut.chen.zhlg.common.utils;


import cn.edu.xmut.chen.zhlg.common.framework.utils.AssertUtils;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.context.annotation.Configuration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt工具类
 *
 * @author zhangmingcheng
 */
@Configuration
public class JwtUtil {

    private static final long EXPIRATION_TIME = 3600000 * 24 * 7; // 24 * 7 hour

    private static final String SECRET = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjY34DFDSSSd";// 秘钥

    private static final String USER_ID = "id";


    /**
     * 生成jwtToken
     *
     */
    public static String generateToken(String id) {
        HashMap<String, Object> map = new HashMap<>();
        map.put(USER_ID, id);
        // 返回jwt字符串
        return Jwts.builder().setClaims(map).setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SECRET).compact();
    }

    /**
     * 校验jwtToken
     *
     */
    public static String validateToken(String token) {
        AssertUtils.assertNotNull(token, ResultType.AGAIN_LOGIN, "当前会话未登录");
        try {
            Map<String, Object> body = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
            String id = (String) (body.get(USER_ID));
            // 断言 id 不为空
            AssertUtils.assertFalse(id == null || id.isEmpty(), ResultType.AGAIN_LOGIN, "未能读取到有效 token");
            return id;
        }catch (Exception e){
            AssertUtils.assertFalse(true, ResultType.AGAIN_LOGIN, "未能读取到有效 token");
            return null;
        }
    }

    public static String getLoginId(String token){
        Map<String, Object> body = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
        String id = (String) (body.get(USER_ID));
        // 断言 id 不为空
        AssertUtils.assertFalse(id == null || id.isEmpty(), ResultType.AGAIN_LOGIN, "未能读取到有效 token");
        return id;
    }


    public static void main(String[] args) {
        String id = "6876ab1fb942fd4f27ff15c6ac4ba1fe";
        String token = generateToken(id);
        System.out.println(token);
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", id);
        token = Jwts.builder().setClaims(map).setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SECRET).compact();
        String result = "";
        try {
            result = validateToken(token);
            System.out.println(result);
        }catch (Exception e){
            System.out.println(e.toString());
        }

    }
}